package cn.caplike.demo.rabbitmq.api.dlx;

import cn.caplike.demo.rabbitmq.api.Application;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author LiKe
 * @version 1.0.0
 * @date 2020-02-19 12:18
 */
public class Producer {

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Application.RABBITMQ_HOST);
        connectionFactory.setPort(Application.RABBITMQ_PORT);
        connectionFactory.setVirtualHost("/");

        // 通过链接工厂创建连接
        Connection connection = connectionFactory.newConnection();

        // 通过连接创建一个 Channel
        Channel channel = connection.createChannel();
        // 指定消息投递模式
        channel.confirmSelect();

        final String exchangeName = "test_dlx_exchange";
        final String routingKey = "dlx.save";

        // 发送消息
        final String msg = "Hello RabbitMQ Send DLX message!";
        for (int idx = 0; idx < 1; idx++) {
            AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
                    .deliveryMode(2)
                    .contentEncoding("UTF-8")
                    // 先启动消费端, 创建常规队列交换机和死信队列交换机, 随后停掉消费端, 10s 后消息会路由到 死信队列上
                    .expiration("10000") // 10s
                    .build();
            // 消息发送到绑定了 DLX 的正常交换机上
            channel.basicPublish(exchangeName, routingKey, false, properties, msg.getBytes());
        }
    }
}
